import express from 'express';
import { body, validationResult } from 'express-validator';
import { executeQuery, getOne } from '../config/database.js';
import { authenticateToken, requireDriver } from '../middleware/auth.js';

const router = express.Router();

// 获取司机信息
router.get('/profile', authenticateToken, requireDriver, async (req, res) => {
  try {
    const driverId = req.user.id;
    
    const driverInfo = await getOne(`
      SELECT 
        u.id, u.name, u.phone,
        u.license_no, u.bus_no
      FROM users u
      WHERE u.id = ? AND u.role = 'driver'
    `, [driverId]);

    res.json({
      success: true,
      data: driverInfo
    });

  } catch (error) {
    console.error('获取司机信息错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器错误'
    });
  }
});









// 获取离园校车名单
router.get('/departure-list', authenticateToken, requireDriver, async (req, res) => {
  try {
    const { date = new Date().toISOString().split('T')[0] } = req.query;
    
    // 获取当前司机信息
    const driver = await getOne(`
      SELECT u.id as driver_id, u.bus_no, u.name as driver_name
      FROM users u
      WHERE u.id = ? AND u.role = 'driver'
    `, [req.user.id]);

    if (!driver) {
      return res.status(404).json({
        success: false,
        message: '司机信息未找到'
      });
    }

    const driverId = driver.driver_id;

    // 获取绑定到该司机的学生的离园记录
    const students = await executeQuery(`
      SELECT 
        ar.id as record_id,
        s.id as student_id, s.student_no, s.name as student_name,
        c.name as class_name, c.grade,
        ar.departure_status, ar.departure_timestamp as departure_time,
        ar.notes,
        -- 移除teacher_name字段，因为数据库中已无相关字段
        bdq.marked_time as bus_marked_time,
        bdq.notes as bus_notes
      FROM students s
      INNER JOIN classes c ON s.class_id = c.id
      LEFT JOIN attendance_records ar ON s.id = ar.student_id AND ar.attendance_date = ?
      LEFT JOIN bus_departure_queue bdq ON s.id = bdq.student_id AND bdq.departure_date = ?
      WHERE s.assigned_bus_id = ? 
        AND (ar.departure_status = 'bus' OR ar.departure_status IS NULL)
      ORDER BY ar.departure_timestamp DESC, s.name
    `, [date, date, driverId]);

    // 统计数据
    const stats = {
      total: students.length,
      marked_bus: students.filter(s => s.departure_status === 'bus').length,
      not_marked: students.filter(s => !s.departure_status || s.departure_status === null).length,
      abnormal: students.filter(s => s.departure_status === 'abnormal').length
    };

    res.json({
      success: true,
      data: {
        date,
        students,
        stats
      }
    });

  } catch (error) {
    console.error('获取离园校车名单错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器错误'
    });
  }
});

// 注意：司机确认功能已移除，司机只需查看名单
// 学生标记校车离园后会自动进入对应司机的队列，无需确认



export default router;